package com.hfzy.ihk.common.core.elasticsearch;

import com.alibaba.fastjson.JSON;
import com.hfzy.ihk.common.core.elasticsearch.entity.OperationErrorMsg;
import com.hfzy.ihk.common.core.elasticsearch.repository.common.OperationErrorMsgRepository;
import com.hfzy.ihk.common.core.elasticsearch.service.EsBaseServiceImpl;
import org.elasticsearch.common.UUIDs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by Administrator on 2018/8/13.
 *
 * @author wws
 */
@Component
public class OperationErrorMsgBiz extends EsBaseServiceImpl<OperationErrorMsg> {

    private static final Logger logger = LoggerFactory.getLogger(OperationErrorMsgBiz.class);

    @Autowired
    OperationErrorMsgRepository operationErrorMsgRepository;

    @Override
    protected ElasticsearchCrudRepository getReposity() {
        return operationErrorMsgRepository;
    }

    public void dealElasticsearchOperation(ElasticsearchOperation elasticsearchOperation, Exception e){

        if(elasticsearchOperation.getData() == null || elasticsearchOperation.getData().isEmpty()){
            logger.warn("关于表操作失败的处理中，发现传入的数据为空！data:{}", JSON.toJSONString(elasticsearchOperation));
            return;
        }

        OperationErrorMsg optErrorMsg = null;
        try {
            optErrorMsg = new OperationErrorMsg();

            optErrorMsg.setId(UUIDs.base64UUID());
            optErrorMsg.setCreateTime(new Date());
            optErrorMsg.setTxId(elasticsearchOperation.getTxId());
            optErrorMsg.setTopic(null);
            optErrorMsg.setPartition(null);
            optErrorMsg.setOptTable(elasticsearchOperation.getOptTable());
            optErrorMsg.setOptMethod(elasticsearchOperation.getOptMethod());
            String json = JSON.toJSONString(elasticsearchOperation.getData());
            optErrorMsg.setJsonArrayMessage(json);
            optErrorMsg.setExceptionMsg(e!=null?e.getMessage():null);

            operationErrorMsgRepository.save(optErrorMsg);
        } catch (Exception e1) {
            logger.warn("关于表操作失败的处理中,数据保存失败，现在存入本地内存，size:{}", ElasticsearchLocalCache.getOptErrorMsgMemoryCacheSize());
            ElasticsearchLocalCache.put(optErrorMsg);
        }
    }
}
